package com.ddwl.goods.service;

import com.alibaba.fastjson.JSON;
import com.ddwl.common.constant.*;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.GateApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.common.util.MySqlUtil;
import com.ddwl.goods.dao.AcademyCategoryDao;
import com.ddwl.goods.dao.AcademyDao;
import com.ddwl.goods.dao.AcademyScanRecordDao;
import com.ddwl.goods.dao.model.Academy;
import com.ddwl.goods.dao.model.AcademyCategory;
import com.ddwl.goods.dao.model.AcademyScanRecord;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.gate.DingTalkBo;
import com.ddwl.schema.bo.goods.*;
import com.ddwl.schema.util.DateUtil;
import com.ddwl.schema.vo.base.PageVo;
import com.ddwl.schema.vo.goods.AcademyListVo;
import com.ddwl.schema.vo.goods.AcademyVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * 商学院service
 * @author wenbin
 */
@Service
public class AcademyService {


    @Resource
    private AcademyCategoryDao academyCategoryDao;

    @Resource
    private AcademyDao academyDao;

    @Resource
    private AcademyScanRecordDao academyScanRecordDao;

    @Resource
    private GateApi gateApi;

    @Resource
    private RabbitTemplate rabbitTemplate;

    //按照sort序号排序
    private String sort ="academySort";

    /**
     * 查询列表
     * @param boPageBo
     * @return
     */
    public PageVo<AcademyVo> academyList(PageBo<QueryAcademyBo> boPageBo) {
        PageHelper.startPage(boPageBo.getPage(),boPageBo.getPageSize(), MySqlUtil.orderBy(boPageBo.getSort(),boPageBo.isAsc()));
        PageInfo<Academy> info = new PageInfo(academyDao.queryAcademy(boPageBo.getParam()));
        List<AcademyVo> list = BeanConverUtils.convertBeanList(info.getList(),AcademyVo.class);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        //填充分类名称
        List<AcademyCategory> academyCategories = academyCategoryDao.selectAll();
        ParamException.isTrue(academyCategories==null||academyCategories.size()==0,"分类为空,请先加分类");
        for (AcademyVo vo:list) {
            for (AcademyCategory ac:academyCategories) {
                if (ac.getId().equals(vo.getAcademyCategoryId())){
                    vo.setAcademyCategoryName(ac.getAcademyCategoryName());
                    break;
                }
            }
        }
        return new PageVo<>(info.getTotal(),boPageBo.getPage(),boPageBo.getPageSize(),list);
    }

    public AcademyVo academyDetail(String academyId){
        return BeanConverUtils.convertBean(academyDao.selectByPrimaryKey(academyId),AcademyVo.class);
    }

    /**
     * 查询明细
     * @param academyId
     * @return
     */
    public AcademyVo academyDetail(String academyId,String userId) {
        ParamException.isBlank(academyId,"文章不存在");
        AcademyVo academy = BeanConverUtils.convertBean(academyDao.selectByPrimaryKey(academyId),AcademyVo.class);
        ParamException.isNull(academy,"文章不存在");

        //填充分类名称
        AcademyCategory academyCategory = academyCategoryDao.selectByPrimaryKey(academy.getAcademyCategoryId());
        if (academyCategory!=null){
            academy.setAcademyCategoryName(academyCategory.getAcademyCategoryName());
        }
        //记录浏览量
        ((AcademyService) AopContext.currentProxy()).academyScanCount(academyId,academy.getAcademyCategoryId(),userId);
        return academy;
    }

    /**
     * 创建文章
     * @param bo
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public void createAcademy(AcademyBo bo, String userId) {
        ParamException.isNotNull(bo.getId(),"分类id不为空");
        ParamException.isBlank(bo.getAcademyCategoryId(),"分类id为空");
        ParamException.isBlank(bo.getTitle(),"标题为空");
        ParamException.isNull(bo.getOldScanCount(),"虚拟阅读量不能为空");

        //标题不能重复
        Academy Academy = new Academy();
        Academy.setTitle(bo.getTitle());
        Academy category = academyDao.selectOne(Academy);
        ParamException.isNotNull(category,"标题重复");

        Academy entity = BeanConverUtils.convertBean(bo, Academy.class);
        entity.setStatus(GoodsEnum.AcademyStatusEnum.PASSED.getCode());
        entity.setSource(GoodsEnum.AcademySourceEnum.CONSOLE.getCode());
        entity.setEffect(0);
        entity.setScanCount(0);
        entity.setCreatedUserId(userId);
        entity.setCreatedUserName("多典学院");
        entity.setModifiedUserId(userId);
        entity.setModifiedUserName("多典学院");
        academyDao.insert(entity);
    }

    /**
     * 修改文章
     * @param bo
     * @return
     */
    @Transactional(rollbackFor = Throwable.class)
    public void updateAcademy(AcademyBo bo,String userId) {
        ParamException.isBlank(bo.getId(),"文章id为空");
        Academy entity = BeanConverUtils.convertBean(bo, Academy.class);
        entity.setModifiedUserId(userId);
        entity.setModifiedUserName("多典学院");
        entity.setScanCount(null);
        academyDao.updateByPrimaryKeySelective(entity);
        //标题不能重复
        if (!StringUtils.hasText(entity.getTitle())){
            Academy Academy = new Academy();
            Academy.setTitle(entity.getTitle());
            List<Academy> academyList = academyDao.select(Academy);
            Boolean check= academyList!=null&&academyList.size()>1;
            ParamException.isTrue(check,"标题重复");
        }
    }

    /**
     * 删除文章
     * @param id
     * @param userId
     * @return
     */
    public void deleteAcademy(String id,String userId) {
        ParamException.isBlank(id,"文章id为空");
        Academy entity = new Academy();
        entity.setId(id);
        entity.setGmtModified(Instant.now());
        entity.setDflag(BaseEnum.DflagEnum.DELETED.getCode());
        entity.setModifiedUserId(userId);
        entity.setModifiedUserName("多典学院");
        academyDao.updateByPrimaryKeySelective(entity);
    }

    /**
     * 记录浏览
     * @param academyId
     * @param academyCategoryId
     * @param userId
     * @return
     */
    @Async
    public void academyScanCount(String academyId,String academyCategoryId,String userId){
        Academy academy = academyDao.selectByPrimaryKey(academyId);
        //更新文章阅读量
        Integer scanCount = null == academy.getScanCount() ? 0 : academy.getScanCount();
        Integer oldScanCount = null == academy.getOldScanCount() ? 0 : academy.getOldScanCount();
        academy.setScanCount(scanCount+1);
        academy.setOldScanCount(oldScanCount+1);
        academyDao.updateScanCount(academy);

        //更新浏览记录
        AcademyScanRecord academyScanRecord = new AcademyScanRecord();
        academyScanRecord.setUserId(userId);
        academyScanRecord.setRecordDate(DateUtil.formatDate(Instant.now()));
        academyScanRecord.setAcademyId(academyId);
        academyScanRecord.setAcademyCategoryId(academyCategoryId);
        AcademyScanRecord record = academyScanRecordDao.selectOne(academyScanRecord);
        AcademyScanRecord update = new AcademyScanRecord();
        //同一天同一用户同一文章算同一个
        if(record!=null){
            update.setId(record.getId());
            update.setScanCount(record.getScanCount()+1);
            academyScanRecordDao.updateByPrimaryKeySelective(update);
        }else{
            update.setScanCount(1);
            update.setRecordDate(DateUtil.formatDate(Instant.now()));
            update.setUserId(userId);
            update.setAcademyCategoryId(academyCategoryId);
            update.setAcademyId(academyId);
            academyScanRecordDao.insert(update);
        }
    }

    /**
     * 查询当前所有文章
     * @return
     */
    public List<AcademyListVo> getAcademyTotal() {
        List<AcademyCategory> academyCategories = academyCategoryDao.selectAllWithEffect(1);
        if (academyCategories==null&&academyCategories.size()!=0){
            return null;
        }
        List<AcademyListVo> list=new ArrayList<>();
        academyCategories.stream().forEach(o->{
            AcademyListVo academyListVo=new AcademyListVo();
            academyListVo.setAcademyCategoryId(o.getId());
            academyListVo.setAcademyCategoryName(o.getAcademyCategoryName());

            QueryAcademyBo bo=new QueryAcademyBo();
            bo.setAcademyCategoryId(o.getId());
            bo.setAcademy(sort);
            bo.setEffect(1);
            List<AcademyVo> academyVos = BeanConverUtils.convertBeanList(academyDao.queryAcademy(bo), AcademyVo.class);
            academyListVo.setAcademyVos(academyVos);
            list.add(academyListVo);
        });
        return list;
    }

    public void publishAcademy(SelfAcademyAddBo bo, String userId, String userName) throws Exception {
        Academy entity = BeanConverUtils.convertBean(bo, Academy.class);
        entity.setStatus(GoodsEnum.AcademyStatusEnum.PENDING.getCode());
        entity.setSource(GoodsEnum.AcademySourceEnum.APP.getCode());
        entity.setEffect(0);
        entity.setScanCount(0);
        entity.setOldScanCount(0);
        entity.setCreatedUserId(userId);
        entity.setCreatedUserName(userName);
        entity.setModifiedUserId(userId);
        entity.setModifiedUserName(userName);
        academyDao.insert(entity);
        //发送钉钉消息
        DingTalkBo bo1=new DingTalkBo();
        bo1.setMessage("");
        bo1.setChannel(StatisticsEnum.channel.UN_APPROVE_ARTICLES.getId());
        rabbitTemplate.convertAndSend(RabbitMqConstants.DINGDING_TALK_MESSAGE, JSON.toJSONString(bo1));
    }


    public void reEditAcademy(SelfAcademyUpdateBo bo, String userId, String userName) {
        Academy exist=academyDao.selectByPrimaryKey(bo.getId());
        ParamException.isNull(exist,"文章不存在");
        Academy entity = BeanConverUtils.convertBean(bo, Academy.class);
        entity.setStatus(GoodsEnum.AcademyStatusEnum.PENDING.getCode());
        entity.setEffect(BaseEnum.StatusEnum.DISABLE.getCode());
        entity.setSource(exist.getSource());
        entity.setScanCount(exist.getScanCount());
        entity.setOldScanCount(exist.getOldScanCount());
        entity.setDflag(BaseEnum.DflagEnum.NOT_DELETE.getCode());
        entity.setCreatedUserId(exist.getCreatedUserId());
        entity.setCreatedUserName(exist.getCreatedUserName());
        entity.setGmtCreated(exist.getGmtCreated());
        entity.setGmtModified(Instant.now());
        entity.setModifiedUserId(userId);
        entity.setModifiedUserName(userName);
        academyDao.updateSelfAcademy(entity);
    }

    public PageVo<AcademyVo> myAcademyPage(PageBo<SelfAcademyQueryBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(),pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(),pageBo.isAsc()));
        PageInfo<Academy> info = new PageInfo(academyDao.getMyAcademyList(pageBo.getParam()));
        List<AcademyVo> list = BeanConverUtils.convertBeanList(info.getList(),AcademyVo.class);
        if (CollectionUtils.isEmpty(list)){
            return new PageVo<>(info.getTotal(),pageBo.getPage(), pageBo.getPageSize(), list);
        }
        //填充分类名称
        List<AcademyCategory> academyCategories = academyCategoryDao.selectAll();
        ParamException.isTrue(academyCategories==null||academyCategories.size()==0,"分类为空,请先加分类");
        if (!CollectionUtils.isEmpty(academyCategories)) {
            for (AcademyVo vo:list) {
                for (AcademyCategory ac:academyCategories) {
                    if (ac.getId().equals(vo.getAcademyCategoryId())){
                        vo.setAcademyCategoryName(ac.getAcademyCategoryName());
                        break;
                    }
                }
            }
        }
        return new PageVo<>(info.getTotal(),pageBo.getPage(),pageBo.getPageSize(),list);
    }

    public void cancelReview(String id) {
        Academy entity = new Academy();
        entity.setId(id);
        entity.setStatus(GoodsEnum.AcademyStatusEnum.DRAFT.getCode());
        academyDao.updateByPrimaryKeySelective(entity);
    }

    public void saveDraft(SelfAcademyAddBo bo, String userId, String userName) {
        Academy entity = BeanConverUtils.convertBean(bo, Academy.class);
        entity.setStatus(GoodsEnum.AcademyStatusEnum.DRAFT.getCode());
        entity.setSource(GoodsEnum.AcademySourceEnum.APP.getCode());
        entity.setEffect(BaseEnum.StatusEnum.DISABLE.getCode());
        entity.setScanCount(0);
        entity.setOldScanCount(0);
        entity.setCreatedUserId(userId);
        entity.setCreatedUserName(userName);
        entity.setModifiedUserId(userId);
        entity.setModifiedUserName(userName);
        academyDao.insert(entity);
    }

    public PageVo<AcademyVo> searchAcademy(PageBo<AcademySearchBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(), pageBo.isAsc()));
        PageInfo<AcademyVo> info = new PageInfo<>(academyDao.searchAcademy(pageBo.getParam()));
        return new PageVo<>(info.getTotal(), pageBo.getPage(), pageBo.getPageSize(), info.getList());
    }

    public Integer academyUnApproveList(QueryAcademyBo pageBo) {
        return academyDao.getAcademyUnApproveList(pageBo);
    }

    public PageVo<AcademyVo> academyPageForApp(PageBo<QueryAcademyBo> pageBo) {
        AcademyCategory academyCategory = academyCategoryDao.selectByPrimaryKey(pageBo.getParam().getAcademyCategoryId());
        ParamException.isNull(academyCategory,"分类不存在");
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize(), MySqlUtil.orderBy(pageBo.getSort(), pageBo.isAsc()));
        PageInfo<Academy> info = new PageInfo<>(academyDao.academyListForApp(pageBo.getParam()));
        List<AcademyVo> list = BeanConverUtils.convertBeanList(info.getList(),AcademyVo.class);
        if (CollectionUtils.isEmpty(list)){
            return new PageVo<>(info.getTotal(),pageBo.getPage(), pageBo.getPageSize(), list);
        }
        list.forEach(academyVo -> academyVo.setAcademyCategoryName(academyCategory.getAcademyCategoryName()));
        return new PageVo<>(info.getTotal(),pageBo.getPage(),pageBo.getPageSize(),list);
    }
}

